import React, { Component } from 'react'

export default class App extends Component {
  state = {
    username: '',
    content: '',
    frame: 'vue',
    sex: 'woman',
    // #1 先准备一个状态来控制 checkbox 中的 value
    fruits: ['apple'],
  }
  handleChange = (e) => {
    this.setState({
      [e.target.name]:
        e.target.type === 'checkbox'
          ? this.state.fruits.includes(e.target.value)
            ? this.state.fruits.filter((item) => item !== e.target.value)
            : [...this.state.fruits, e.target.value]
          : e.target.value,
    })
  }
  render() {
    return (
      <ul>
        <li>
          用户名：
          <input type='text' value={this.state.username} onChange={this.handleChange} name='username' />
        </li>
        <li>
          <textarea value={this.state.content} cols='30' rows='10' onChange={this.handleChange} name='content'></textarea>
        </li>
        <li>
          <select value={this.state.frame} onChange={this.handleChange} name='frame'>
            <option value='react'>React</option>
            <option value='vue'>Vue</option>
            <option value='angular'>Angular</option>
          </select>
        </li>
        <li>
          <label htmlFor='man'>男</label>
          <input type='radio' value='man' id='man' checked={this.state.sex === 'man'} onChange={this.handleChange} name='sex' />
          <label htmlFor='woman'>女</label>
          <input type='radio' value='woman' id='woman' checked={this.state.sex === 'woman'} onChange={this.handleChange} name='sex' />
          <label htmlFor='unknown'>未知</label>
          <input type='radio' value='unknown' id='unknown' checked={this.state.sex === 'unknown'} onChange={this.handleChange} name='sex' />
        </li>
        <li>
          {/* #2 用状态 username 和 input 的 checked 进行绑定 */}
          <label htmlFor='apple'>Apple</label>
          <input type='checkbox' value='apple' id='apple' checked={this.state.fruits.includes('apple')} onChange={this.handleChange} name='fruits' />
          <label htmlFor='orange'>Orange</label>
          <input type='checkbox' value='orange' id='orange' checked={this.state.fruits.includes('orange')} onChange={this.handleChange} name='fruits' />
        </li>
      </ul>
    )
  }
}
